package pers.dawnyang.modular.monitor.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import pers.dawnyang.common.domain.Result;
import pers.dawnyang.common.domain.entity.SysLoginLog;
import pers.dawnyang.common.util.ResultUtil;
import pers.dawnyang.modular.system.service.LoginLogService;

/**
 * 在线用户监控
 * 
 * @author dawn yang
 * @date 2021/04/20
 */

@Controller
@RequestMapping("/monitor/userOnline")
public class UserOnlineController {

  @Autowired
  private LoginLogService loginLogService;

  @Autowired
  @Qualifier("memorySessionDAO")
  private SessionDAO sessionDAO;

  @RequiresPermissions("monitor:userOnline:index")
  @GetMapping("/index")
  public String index() {
    return "/monitor/userOnline/index";
  }

  @RequiresPermissions("monitor:userOnline:list")
  @PostMapping("/getPage")
  @ResponseBody
  public Result<Page<SysLoginLog>> getPage(Page<SysLoginLog> page, SysLoginLog req) {
    // 获取存在的所有SESSION账号
    Collection<Session> sessions = sessionDAO.getActiveSessions();
    List<String> sessionIdList = new ArrayList<>();
    for (Session session : sessions) {
      sessionIdList.add(session.getId().toString());
    }
    LambdaQueryWrapper<SysLoginLog> lqw = new LambdaQueryWrapper<>();
    lqw.in(SysLoginLog::getSessionId, sessionIdList);
    lqw.like(StringUtils.isNoneBlank(req.getUserCode()), SysLoginLog::getUserCode,
        req.getUserCode());
    lqw.like(StringUtils.isNoneBlank(req.getLoginIp()), SysLoginLog::getLoginIp, req.getLoginIp());
    Page<SysLoginLog> pageRes = loginLogService.page(page, lqw);
    return ResultUtil.success(pageRes);
  }

}
